package com.zjut.zs.user.dao;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.util.module.PageModule;
import com.zjut.an.util.tools.AESUtils;
import com.zjut.zs.userinfo.dao.ZsUserinfo;

/**
 * A data access object (DAO) providing persistence and search support for
 * ZsUser entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.zjut.zs.user.dao.ZsUser
 * @author MyEclipse Persistence Tools
 */

public class ZsUserDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory.getLogger(ZsUserDAO.class);
	// property constants
	public static final String ID = "id";
	public static final String US_ID = "usId";
	public static final String US_BMXH = "usBmxh";
	public static final String US_NAME = "usName";
	public static final String US_IDCARD = "usIdcard";
	public static final String US_PASSWORD = "usPassword";
	public static final String US_EMAIL = "usEmail";
	public static final String US_MOBILE = "usMobile";
	public static final String OPEN_ID = "openId";
	public static final String WX_NAME = "wxName";
	public static final String WX_ICON = "wxIcon";
	public static final String US_ACTIVE = "usActive";
	public static final String US_YUN = "usYun";

	protected void initDao() {
		// do nothing
	}

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(ID));			
		}
	}
	
	public void save(ZsUser transientInstance) {
		log.debug("saving ZsUser instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void update(ZsUser transientInstance) {
		log.debug("updating ZsUser instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	
	public void delete(ZsUser persistentInstance) {
		log.debug("deleting ZsUser instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ZsUser findById(java.lang.String usId) {
		log.debug("getting ZsUser instance with usId: " + usId);
		try {
			ZsUser instance = (ZsUser) getHibernateTemplate().get(
					"com.zjut.zs.user.dao.ZsUser", usId);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ZsUser instance) {
		log.debug("finding ZsUser instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ZsUser instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ZsUser as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUsName(Object usName) {
		return findByProperty(US_NAME, usName);
	}

	public List findByUsIdcard(Object usIdcard) {
		return findByProperty(US_IDCARD, usIdcard);
	}

	public List findByUsPassword(Object usPassword) {
		return findByProperty(US_PASSWORD, usPassword);
	}

	public List findByUsEmail(Object usEmail) {
		return findByProperty(US_EMAIL, usEmail);
	}

	public List findByUsMobile(Object usMobile) {
		return findByProperty(US_MOBILE, usMobile);
	}

	public List findByOpenId(Object openId) {
		return findByProperty(OPEN_ID, openId);
	}

	public List findByWxName(Object wxName) {
		return findByProperty(WX_NAME, wxName);
	}

	public List findByWxIcon(Object wxIcon) {
		return findByProperty(WX_ICON, wxIcon);
	}

	public List findByUsActive(Object usActive) {
		return findByProperty(US_ACTIVE, usActive);
	}

	public List findByUsYun(Object usYun) {
		return findByProperty(US_YUN, usYun);
	}

	public List findAll() {
		log.debug("finding all ZsUser instances");
		try {
			String queryString = "from ZsUser";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ZsUser merge(ZsUser detachedInstance) {
		log.debug("merging ZsUser instance");
		try {
			ZsUser result = (ZsUser) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ZsUser instance) {
		log.debug("attaching dirty ZsUser instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ZsUser instance) {
		log.debug("attaching clean ZsUser instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static ZsUserDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ZsUserDAO) ctx.getBean("ZsUserDAO");
	}

	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final ZsUser obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(ZsUser.class);
			
			if (!isEmpty(obj.getUsName())) {
				String name = AESUtils.AESEncryptDemo(obj.getUsName());
				criteria.add(Restrictions.eq(US_NAME, name));
			}
			if (!isEmpty(obj.getUsBmxh())) {
				criteria.add(Restrictions.eq(US_BMXH, obj.getUsBmxh()));
			}
			if (!isEmpty(obj.getUsIdcard())) {
				criteria.add(Restrictions.eq(US_IDCARD, obj.getUsIdcard()));
			}
			if (!isEmpty(obj.getUsPassword())) {
				criteria.add(Restrictions.eq(US_PASSWORD, obj.getUsPassword()));
			}
			if (!isEmpty(obj.getUsEmail())) {
				criteria.add(Restrictions.eq(US_EMAIL, obj.getUsEmail()));
			}
			if (!isEmpty(obj.getUsMobile())) {
				criteria.add(Restrictions.eq(US_MOBILE, obj.getUsMobile()));
			}
			if (!isEmpty(obj.getOpenId())) {
				criteria.add(Restrictions.eq(OPEN_ID, obj.getOpenId()));
			}
			if (!isEmpty(obj.getWxName())) {
				criteria.add(Restrictions.eq(WX_NAME, obj.getWxName()));
			}
			if (!isEmpty(obj.getWxIcon())) {
				criteria.add(Restrictions.eq(WX_ICON, obj.getWxIcon()));
			}
			if (!isEmpty(obj.getUsActive())) {
				criteria.add(Restrictions.eq(US_ACTIVE, obj.getUsActive()));
			}
			if (!isEmpty(obj.getUsYun())) {
				criteria.add(Restrictions.eq(US_YUN, obj.getUsYun()));
			}
			//补充
			
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final ZsUser obj) {
		log.debug("finding the number of ZsUser instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(ZsUser.class);
			
			if (!isEmpty(obj.getUsName())) {
				String name = AESUtils.AESEncryptDemo(obj.getUsName());
				criteria.add(Restrictions.eq(US_NAME, name));
			}
			if (!isEmpty(obj.getUsBmxh())) {
				criteria.add(Restrictions.eq(US_BMXH, obj.getUsBmxh()));
			}
			if (!isEmpty(obj.getUsIdcard())) {
				criteria.add(Restrictions.eq(US_IDCARD, obj.getUsIdcard()));
			}
			if (!isEmpty(obj.getUsPassword())) {
				criteria.add(Restrictions.eq(US_PASSWORD, obj.getUsPassword()));
			}
			if (!isEmpty(obj.getUsEmail())) {
				criteria.add(Restrictions.eq(US_EMAIL, obj.getUsEmail()));
			}
			if (!isEmpty(obj.getUsMobile())) {
				criteria.add(Restrictions.eq(US_MOBILE, obj.getUsMobile()));
			}
			if (!isEmpty(obj.getOpenId())) {
				criteria.add(Restrictions.eq(OPEN_ID, obj.getOpenId()));
			}
			if (!isEmpty(obj.getWxName())) {
				criteria.add(Restrictions.eq(WX_NAME, obj.getWxName()));
			}
			if (!isEmpty(obj.getWxIcon())) {
				criteria.add(Restrictions.eq(WX_ICON, obj.getWxIcon()));
			}
			if (!isEmpty(obj.getUsActive())) {
				criteria.add(Restrictions.eq(US_ACTIVE, obj.getUsActive()));
			}
			if (!isEmpty(obj.getUsYun())) {
				criteria.add(Restrictions.eq(US_YUN, obj.getUsYun()));
			}
			//补充
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of ZsUser instance failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List findByHql(final int pageNumber ,final int pageSize, final String hql, final Object[] values){
		log.debug("finding ZsUser instance by hql");
	    return (List<ZsUser>) super.getHibernateTemplate().execute(new HibernateCallback(){
	        public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            Query query=session.createQuery(hql);
	            if (values != null) {// 为hql语句传入参数
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
	            return query.setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
	        }
	    });
	}

	@SuppressWarnings("unchecked")
	public int findCountByHql(final String hql, final Object[] values) {
		log.debug("finding the number of ZsUser instance");
		try {
			return (Integer) super.getHibernateTemplate().execute(new HibernateCallback(){
		        public Object doInHibernate(Session session) throws HibernateException, SQLException {
		            Query query=session.createQuery(hql);
		            if (values != null) {// 为hql语句传入参数
						for (int i = 0; i < values.length; i++) {
							query.setParameter(i, values[i]);
						}
					}
					return ((Long)query.uniqueResult()).intValue();
		        }
		    });
		} catch (RuntimeException re) {
			log.error("find the number of ZsUser instance failed", re);
			throw re;
		}
	}

	public void excuteHql(String hql,String... value) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		try {
			Query query = session.createQuery(hql);
			for (int i = 0; i < value.length; i++) {
				query.setString(i,value[i]);
			}
			query.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			session.close();
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}
}